package com.baitai.system.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baitai.common.core.domain.entity.SysRole;
import com.baitai.common.core.domain.entity.SysUser;
import com.baitai.common.utils.*;
import com.baitai.system.domain.vo.IncomeManagementStatementVo;
import com.baitai.system.mapper.SysUserMapper;
import org.apache.http.util.Asserts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.baitai.system.mapper.IncomeManagementStatementMapper;
import com.baitai.system.domain.IncomeManagementStatement;
import com.baitai.system.service.IIncomeManagementStatementService;

import static com.baitai.common.utils.PageUtils.startPage;

/**
 * 收益管理Service业务层处理
 *
 * @author xx
 * @date 2024-08-26
 */
@Service
public class IncomeManagementStatementServiceImpl implements IIncomeManagementStatementService {
    @Autowired
    private IncomeManagementStatementMapper incomeManagementStatementMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Value("${taku.url}")
    private String url;

    @Value("${taku.publisher-key}")
    private String publisherKey;

    @Value("${sigmob.url}")
    private String sigmobUrl;


    /**
     * 查询收益管理
     *
     * @param id 收益管理主键
     * @return 收益管理
     */
    @Override
    public IncomeManagementStatement selectIncomeManagementStatementById(Long id) {
        return incomeManagementStatementMapper.selectIncomeManagementStatementById(id);
    }

    /**
     * 查询收益管理列表
     *
     * @param incomeManagementStatement 收益管理
     * @return 收益管理
     */
    @Override
    public List<IncomeManagementStatement> selectIncomeManagementStatementList(IncomeManagementStatementVo incomeManagementStatement) {
        SysUser sysUser = sysUserMapper.selectUserById(SecurityUtils.getUserId());
        Boolean flag = false;
        if (sysUser.getRoles() != null && sysUser.getRoles().size() > 0) {
            for (SysRole item : sysUser.getRoles()) {
                if (item.getRoleId() == 2L) {
                    flag = true;
                }
            }
        }
        if (!sysUser.isAdmin()) {
            if (flag) {
                List<String> userIds = sysUserMapper.selectByAncestor(SecurityUtils.getUserId());
                if (userIds != null && userIds.size() > 0) {
                    incomeManagementStatement.setUserIds(userIds);
                }
            } else {
                incomeManagementStatement.setAgentId(SecurityUtils.getUserId());
            }
        }
        startPage();
        List<IncomeManagementStatement> result = incomeManagementStatementMapper.selectIncomeManagementStatementList(incomeManagementStatement);
        resultList(sysUser.isAdmin(), flag, result);
        return result;
    }

    private void resultList(boolean isAdmin, boolean isManager, List<IncomeManagementStatement> result) {
        for (IncomeManagementStatement managementStatement : result) {
            setManagementStatementNumber(isAdmin, isManager, managementStatement);
        }
    }

    private void setManagementStatementNumber(boolean isAdmin, boolean isManager, IncomeManagementStatement managementStatement) {
        String amount = managementStatement.getIncomeAmount();
        String amountOfExposure = managementStatement.getAmountOfExposure();
        String clickVolume = managementStatement.getClickVolume();
        String clickRate = managementStatement.getClickRate();
        String ecmp = managementStatement.getEcmp();
//        String ecpc = managementStatement.getEcpc();
        if (StringUtils.isNotEmpty(managementStatement.getAdminRate())) {
            amount = getNumber(amount, managementStatement.getAdminRate(), "1", false);
            amountOfExposure = getNumber(amountOfExposure, managementStatement.getAdminRate(), "0", false);
            clickVolume = getNumber(clickVolume, managementStatement.getAdminRate(), "0", false);
            clickRate = getNumber(clickRate, managementStatement.getAdminRate(), "1", true);
            ecmp = getNumber(ecmp, managementStatement.getAdminRate(), "1", false);
//            ecpc = getNumber(ecpc, managementStatement.getAdminRate());
        }
        if (!isManager && !isAdmin) {
            if (StringUtils.isNotEmpty(managementStatement.getManagerRate())) {
                amount = getNumber(amount, managementStatement.getManagerRate(), "1", false);
                amountOfExposure = getNumber(amountOfExposure, managementStatement.getManagerRate(), "0", false);
                clickVolume = getNumber(clickVolume, managementStatement.getManagerRate(), "0", false);
                clickRate = getNumber(clickRate, managementStatement.getManagerRate(), "1", true);
                ecmp = getNumber(ecmp, managementStatement.getManagerRate(), "1", false);
//                ecpc = getNumber(ecpc, managementStatement.getManagerRate());
            }
        }
        managementStatement.setIncomeAmount(amount);
        managementStatement.setAmountOfExposure(amountOfExposure);
        managementStatement.setClickVolume(clickVolume);
        managementStatement.setClickRate(clickRate);
        managementStatement.setEcmp(ecmp);
//        managementStatement.setEcpc(ecpc);
    }

    /**
     * 新增收益管理
     *
     * @param incomeManagementStatement 收益管理
     * @return 结果
     */
    @Override
    public int insertIncomeManagementStatement(IncomeManagementStatement incomeManagementStatement) {
        setRate(incomeManagementStatement);
        return incomeManagementStatementMapper.insertIncomeManagementStatement(incomeManagementStatement);
    }

    /**
     * 修改收益管理
     *
     * @param incomeManagementStatement 收益管理
     * @return 结果
     */
    @Override
    public int updateIncomeManagementStatement(IncomeManagementStatement incomeManagementStatement) {
        setRate(incomeManagementStatement);
        return incomeManagementStatementMapper.updateIncomeManagementStatement(incomeManagementStatement);
    }

    /**
     * 批量删除收益管理
     *
     * @param ids 需要删除的收益管理主键
     * @return 结果
     */
    @Override
    public int deleteIncomeManagementStatementByIds(Long[] ids) {
        return incomeManagementStatementMapper.deleteIncomeManagementStatementByIds(ids);
    }

    /**
     * 删除收益管理信息
     *
     * @param id 收益管理主键
     * @return 结果
     */
    @Override
    public int deleteIncomeManagementStatementById(Long id) {
        return incomeManagementStatementMapper.deleteIncomeManagementStatementById(id);
    }

    @Override
    public List<SysUser> getUserList(Long userId) {
        List<String> userIds = null;
        if (!"1".equals(isAdmin(userId))) {
            userIds = sysUserMapper.selectByAncestor(userId);
        }
        return sysUserMapper.getUserList(userIds);
    }

    public String isAdmin(Long userId) {

        SysUser sysUser = sysUserMapper.selectUserById(userId);
        if (sysUser.isAdmin()) {
            return "1";
        }
        return "0";
    }

    @Override
    public String getPermission(Long userId) {
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        Boolean flag = false;
        if (sysUser.getRoles() != null && sysUser.getRoles().size() > 0) {
            for (SysRole item : sysUser.getRoles()) {
                if (item.getRoleId() == 2L) {
                    flag = true;
                }
            }
        }
        if (sysUser.isAdmin() || flag) {
            return "1";
        }
        return "2";
    }

    @Override
    public int setRatio(Long userId, String ratio) {
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        sysUser.setYieldRate(ratio);
        return sysUserMapper.updateUser(sysUser);
    }

    @Override
    public String getRatio(Long userId) {
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        return sysUser.getYieldRate();
    }

    @Override
    public String getRowRatio(Long id) {
        return incomeManagementStatementMapper.selectIncomeManagementStatementById(id).getManagerRate();
    }

    private void setRate(IncomeManagementStatement incomeManagementStatement) {
        SysUser curr = sysUserMapper.selectUserById(incomeManagementStatement.getAgentId());
        if (StringUtils.isNotEmpty(curr.getAncestor())) {
            SysUser admin = sysUserMapper.selectUserById(1l);
            if (StringUtils.isNotEmpty(admin.getYieldRate())) {
                incomeManagementStatement.setAdminRate(admin.getYieldRate());
            }
            SysUser manager = null;
            String[] ids = curr.getAncestor().split(",");
            if (ids.length > 0) {
                if ("1".equals(ids[0]) && ids.length > 1) {
                    manager = sysUserMapper.selectUserById(Long.parseLong(ids[1]));
                } else {
                    manager = sysUserMapper.selectUserById(Long.parseLong(ids[0]));
                }
            }
            if (manager != null && StringUtils.isNotEmpty(manager.getYieldRate())) {
                incomeManagementStatement.setManagerRate(manager.getYieldRate());
            }
        }
    }

    private String getNumber(String number, String yieldRate, String str, Boolean isRate) {
        BigDecimal value = new BigDecimal(yieldRate);
        value = value.multiply(new BigDecimal(0.01));
        BigDecimal bigDecimalNumber = new BigDecimal(number);
        if ("1".equals(str)) {
            if (isRate) {
                return bigDecimalNumber.multiply(new BigDecimal(100)).multiply(value).setScale(2, RoundingMode.HALF_UP).toString();
            }
            return bigDecimalNumber.multiply(value).setScale(2, RoundingMode.HALF_UP).toString();
        } else {
            return bigDecimalNumber.multiply(value).setScale(0, RoundingMode.HALF_UP).toString();
        }
    }

    @Override
    public int setRowRatio(IncomeManagementStatement incomeManagementStatement) {
        return incomeManagementStatementMapper.updateManagerRate(incomeManagementStatement);
    }


    @Override
    public void getFullReport() {
        getTakuReport();
        getSigmobReport();
    }

    //sigmob收益拉取
    public void getSigmobReport() {

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); // 设置时间格式
        Date date = DateUtils.yesterdayStart();
        String datestr = formatter.format(date);
        Map<String, String> params = new HashMap<String, String>();
        params.put("start_date", datestr);
        params.put("end_date", datestr);

        params.put("group_by", "placement");
        params.put("page_size", "1");
        System.out.println("----------------------"+datestr);
        JSONObject result = JSONObject.parseObject(SigmobUtils.getData(sigmobUrl, params));
        if (result != null && StringUtils.isNotEmpty(result.getString("code")) && result.getString("code").equals("200")) {
            SysUser admin = sysUserMapper.selectUserById(1l);
            JSONObject resultData = JSONObject.parseObject(result.getString("data"));
            if (resultData != null) {
                JSONArray listJS = resultData.getJSONArray("list");
                for (int i = 0; i < listJS.size(); i++) {
                    JSONObject placement = listJS.getJSONObject(i);
//                    JSONObject placement = record.getJSONObject("placement");
                    String placementId = placement.getString("placement_id");
                    IncomeManagementStatement statement = incomeManagementStatementMapper.selectIncomeManagementStatementByPlacementId(placementId, DateUtils.yesterdayStart(), DateUtils.yesterdayEnd());
                    SysUser manager = sysUserMapper.selectUserByPlacementId(placementId);
                    if (statement == null) {
                        if (manager != null) {
                            SysUser channel = sysUserMapper.selectUserByParentId(manager.getUserId());
                            if (channel != null) {
                                IncomeManagementStatement incomeManagementStatement = new IncomeManagementStatement();
                                if (StringUtils.isNotEmpty(admin.getYieldRate())) {
                                    incomeManagementStatement.setAdminRate(admin.getYieldRate());
                                }
                                if (StringUtils.isNotEmpty(manager.getYieldRate())) {
                                    incomeManagementStatement.setManagerRate(manager.getYieldRate());
                                }
                                incomeManagementStatement.setAgentId(channel.getUserId());
                                incomeManagementStatement.setAgentName(channel.getNickName());
                                incomeManagementStatement.setAmountOfExposure(placement.getString("impression"));
                                incomeManagementStatement.setClickVolume(placement.getString("click"));
                                incomeManagementStatement.setClickRate(placement.getString("ctr"));
                                incomeManagementStatement.setIncomeAmount(placement.getString("revenue"));
                                incomeManagementStatement.setEcmp(placement.getString("ecpm"));
                                incomeManagementStatement.setPlacementId(placementId);
                                if (placement.containsKey("placement_name") && StringUtils.isNotEmpty(placement.getString("placement_name"))) {
                                    if (placement.getString("placement_name").length() >= 2) {
                                        incomeManagementStatement.setType(placement.getString("placement_name").substring(0, 2));
                                    } else {
                                        incomeManagementStatement.setType(placement.getString("placement_name"));
                                    }
                                } else {
                                    incomeManagementStatement.setType("--");
                                }

//                                incomeManagementStatement.setCreateTime(DateUtils.afterDay("1"));
                                incomeManagementStatement.setCreateTime(date);
                                incomeManagementStatementMapper.insertIncomeManagementStatement(incomeManagementStatement);
                            }
                        }
                    } else {
                        SysUser channel = sysUserMapper.selectUserByParentId(manager.getUserId());
                        if (channel != null) {
                            if (StringUtils.isNotEmpty(admin.getYieldRate())) {
                                statement.setAdminRate(admin.getYieldRate());
                            }
                            if (StringUtils.isNotEmpty(manager.getYieldRate())) {
                                statement.setManagerRate(manager.getYieldRate());
                            }
                            statement.setAgentId(channel.getUserId());
                            statement.setAgentName(channel.getNickName());
                            statement.setAmountOfExposure(placement.getString("impression"));
                            statement.setClickVolume(placement.getString("click"));
                            statement.setClickRate(placement.getString("ctr"));
                            statement.setIncomeAmount(placement.getString("revenue"));
                            statement.setEcmp(placement.getString("ecpm"));
                            statement.setPlacementId(placementId);
                            if (placement.containsKey("placement_name") && StringUtils.isNotEmpty(placement.getString("placement_name"))) {
                                if (placement.getString("placement_name").length() >= 2) {
                                    statement.setType(placement.getString("placement_name").substring(0, 2));
                                } else {
                                    statement.setType(placement.getString("placement_name"));
                                }
                            } else {
                                statement.setType("--");
                            }
//                            statement.setUpdateTime(DateUtils.afterDay("1"));
                            statement.setUpdateTime(date);
                            incomeManagementStatementMapper.updateIncomeManagementStatement(statement);
                        }
                    }
                }
            }
        }

    }


    //taku收益拉取
    public void getTakuReport() {
        SysUser admin = sysUserMapper.selectUserById(1l);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        Date date = DateUtils.yesterdayStart();
        String datestr = formatter.format(date);

        JSONObject result = TakuUtil.getFullReport(datestr, datestr, url, publisherKey);
        JSONArray records = result.getJSONArray("records");
        for (int i = 0; i < records.size(); i++) {
            JSONObject record = records.getJSONObject(i);
            JSONObject placement = record.getJSONObject("placement");
            String placementId = placement.getString("id");
            IncomeManagementStatement statement = incomeManagementStatementMapper.selectIncomeManagementStatementByPlacementId(placementId, DateUtils.yesterdayStart(), DateUtils.yesterdayEnd());
            SysUser manager = sysUserMapper.selectUserByPlacementId(placementId);
            if (statement == null) {
                if (manager != null) {
                    SysUser channel = sysUserMapper.selectUserByParentId(manager.getUserId());
                    if (channel != null) {
                        IncomeManagementStatement incomeManagementStatement = new IncomeManagementStatement();
                        if (StringUtils.isNotEmpty(admin.getYieldRate())) {
                            incomeManagementStatement.setAdminRate(admin.getYieldRate());
                        }
                        if (StringUtils.isNotEmpty(manager.getYieldRate())) {
                            incomeManagementStatement.setManagerRate(manager.getYieldRate());
                        }
                        incomeManagementStatement.setAgentId(channel.getUserId());
                        incomeManagementStatement.setAgentName(channel.getNickName());
                        incomeManagementStatement.setAmountOfExposure(record.getString("impression"));
                        incomeManagementStatement.setClickVolume(record.getString("click"));
                        incomeManagementStatement.setClickRate(record.getString("ctr"));
                        incomeManagementStatement.setIncomeAmount(record.getString("cy_estimate_revenue"));
                        incomeManagementStatement.setEcmp(record.getString("cy_estimate_revenue_ecpm"));
                        incomeManagementStatement.setPlacementId(placementId);
                        if (placement.containsKey("name") && StringUtils.isNotEmpty(placement.getString("name"))) {
                            if (placement.getString("name").length() >= 2) {
                                incomeManagementStatement.setType(placement.getString("name").substring(0, 2));
                            } else {
                                incomeManagementStatement.setType(placement.getString("name"));
                            }
                        } else {
                            incomeManagementStatement.setType("--");
                        }
                        incomeManagementStatement.setCreateTime(date);
                        incomeManagementStatementMapper.insertIncomeManagementStatement(incomeManagementStatement);
                    }
                }
            } else {
                SysUser channel = sysUserMapper.selectUserByParentId(manager.getUserId());
                if (channel != null) {
                    if (StringUtils.isNotEmpty(admin.getYieldRate())) {
                        statement.setAdminRate(admin.getYieldRate());
                    }
                    if (StringUtils.isNotEmpty(manager.getYieldRate())) {
                        statement.setManagerRate(manager.getYieldRate());
                    }
                    statement.setAgentId(channel.getUserId());
                    statement.setAgentName(channel.getNickName());
                    statement.setAmountOfExposure(record.getString("impression"));
                    statement.setClickVolume(record.getString("click"));
                    statement.setClickRate(record.getString("ctr"));
                    statement.setIncomeAmount(record.getString("cy_estimate_revenue"));
                    statement.setEcmp(record.getString("cy_estimate_revenue_ecpm"));
                    statement.setPlacementId(placementId);
                    if (placement.containsKey("name") && StringUtils.isNotEmpty(placement.getString("name"))) {
                        if (placement.getString("name").length() >= 2) {
                            statement.setType(placement.getString("name").substring(0, 2));
                        } else {
                            statement.setType(placement.getString("name"));
                        }
                    } else {
                        statement.setType("--");
                    }
//                    statement.setUpdateTime(DateUtils.afterDay("1"));
                    statement.setUpdateTime(date);
                    incomeManagementStatementMapper.updateIncomeManagementStatement(statement);
                }
            }
        }
    }
}
